<template>
  <div class="container" :class="{ 'fullscreen-mode': isFullscreen }">
    <div class="top">
      <ps-header :title="title" :showDecoration5="false">
        <template #header>
          <select
            class="chart-select"
            v-model="active"
            @change="loadData"
            v-if="!isFullscreen"
          >
            <option :value="''">全部</option>
            <option
              v-for="item in options"
              :key="item.Udef1"
              :value="item.Udef1"
            >
              {{ item.Udef1 }}
            </option>
          </select>

          <select
            class="chart-select"
            v-model="activeLineID"
            @change="loadData"
            v-if="!isFullscreen"
          >
            <option :value="''">全部</option>
            <option
              v-for="item in lineList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.LineName }}
            </option>
          </select>
        </template>
      </ps-header>
    </div>

    <div class="productionPanel3-content">
      <div class="dashboard-row" style="display: block; overflow: hidden">
        <ps-machine2 :params="params" :rows="3" ref="psMachineRef" />
      </div>
      <div class="dashboard-row bottom-row">
        <div class="full-widget">
          <productionBoard21 :key="key" :gxmc="active" :scdw="activeLineID" />
        </div>
        <productionBoard19
          :key="key"
          class="full-widget"
          :activeLineID="activeLineID"
          :active="active"
        />
        <productionBoard10
          :key="key"
          class="full-widget"
          :activeLineID="activeLineID"
          :active="active"
        />
      </div>
    </div>
  </div>
</template>

<script setup name="visualTopicPannel">
import { getgxdlxxNow } from "@/api/processClassNow.js";
import { userStore as useUserStore } from "@/pinia/user";

import { useLocalStorage } from "@vueuse/core";
import { storeToRefs } from "pinia";
import { prdPrdLineApi } from "@/api/globalApi";
import productionBoard21 from "@/views/visual/modules/productionBoard21.vue";
import productionBoard19 from "@/views/visual/modules/productionBoard19.vue";
import productionBoard10 from "@/views/visual/modules/productionBoard10.vue";

import moment from "moment";
const updateTime = ref("");
const timer = ref();
const key = ref(0);
const psMachineRef = ref();
const time = ref(300);
const total = ref();
const scrollBoardRef = ref();
const options = ref([]);
const lineList = ref([]);
const socket = inject("socket");
const userStore = useUserStore();
const { profile } = storeToRefs(userStore);
const isFullscreen = inject("isFullScreen");
const active = useLocalStorage("visualTopicPannel.active", "");
const activeLineID = useLocalStorage("visualTopicPannel.activeLineID", "");
const scrollContentRef = ref();

const params = computed(() => {
  return {
    lineID: active.value,
    prodLine: activeLineID.value,
  };
});

const startAutoScroll = () => {
  const container = scrollContentRef.value;

  if (!container) return;

  // 获取第一个子项的高度
  const itemHeight = container.children[0]?.offsetHeight || 100;

  if (itemHeight === 0) return;

  // 设置动画持续时间（根据内容高度动态调整）
  const duration = itemHeight * 0.05; // 每像素滚动时间（单位：秒）
  container.style.animationDuration = `${duration}s`;
};

onMounted(async () => {
  await nextTick(); // 等待 DOM 更新
  startAutoScroll();
});

// 自动更新时间五分钟
const updateData = () => {
  timer.value = setInterval(() => {
    if (time.value > 0) {
      time.value--;
      const duration = moment.duration(time.value * 1000); // 转换为毫秒
      const minutes = duration.asMinutes(); // 总分钟数（包含小数部分）
      const wholeMinutes = Math.floor(minutes); // 取整得到分钟数
      const remainingSeconds = Math.round((minutes - wholeMinutes) * 60); // 计算剩余的秒数
      updateTime.value = `${wholeMinutes}分${remainingSeconds}秒`;
    } else {
      time.value = 300;
      key.value++;
    }
  }, 1000);
};

// 动态控制标题内容
const title = computed(() =>
  active.value
    ? profile.value.company + "-" + active.value
    : profile.value.company
);

const loadData = () => {
  psMachineRef.value.loadData(params.value);
};

const loadLineList = async () => {
  const { data } = await prdPrdLineApi();
  lineList.value = data;
};

/**
 * @description: 加载工序大类选项
 */
const loadProcessOptions = async () => {
  const { data } = await getgxdlxxNow();
  options.value = data;
};

const keyResize = () => {
  key.value++;
};

onMounted(() => {
  window.addEventListener("fullscreenchange", keyResize);
});

onMounted(loadProcessOptions);
onMounted(loadLineList);
onMounted(updateData);
onUnmounted(() => {
  window.removeEventListener("fullscreenchange", keyResize);
  timer.value && clearInterval(timer.value);
  socket.removeAllListeners("report-system-update");
});
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  background-image: url("../../assets/image/visualization-bg.png");
  display: flex;
  flex-direction: column;

  .top {
    .tools {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        flex: 1;

        :deep(.el-button:hover) {
          background-color: #ffa500;
          border-color: #ffa500;
        }
      }

      .right {
        color: #fff;
        font-size: 18px;
        font-weight: bold;
        margin-left: auto;
        margin-right: 30px;
      }
    }
  }
}

:deep(.dv-scroll-board .rows .row-item) {
  font-size: 20px;
  letter-spacing: 0px;
}

:deep(.dv-scroll-board .header .header-item) {
  font-size: 20px;
  letter-spacing: 0px;
}

:deep .progress-bar {
  position: relative; /* 定位基准 */
  width: 100%;
  height: 10px;
  background-color: #2d3d4d; /* 背景色（未完成部分的颜色） */
  border-radius: 10px;
  overflow: hidden;
  margin-top: 2%;
}

:deep .progress {
  position: absolute; /* 绝对定位，从左侧开始填充 */
  left: 0; /* 强制从左侧开始 */
  top: 0;
  height: 100%;
  background: linear-gradient(to right, #4fd2dd, #00f2fe); /* 从左到右渐变 */
  z-index: 1; /* 确保在文字下方 */
  transition: width 0.3s; /* 可选：添加过渡动画 */
}

:deep .text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 12px;
  z-index: 2; /* 确保文字在顶部 */
  pointer-events: none; /* 防止文字拦截点击事件 */
}
.productionPanel3-content {
  height: calc(100vh - 200px); /* 根据顶部栏高度调整 */
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 15px;
}

/* 行布局 */
.dashboard-row {
  display: grid;
  gap: 15px;
  flex: 1;
}

/* 第一行布局 */
.dashboard-row:first-child {
  grid-template-columns: 1fr 4fr; /* 窄组件:主表格 = 1:4 */
  min-height: 45vh;
}

/* 组件容器 */
.widget-group {
  display: grid;
  grid-template-rows: 1fr 1fr; /* 上下等分 */
  gap: 15px;
}

/* 主表格样式 */
.main-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 底部行布局 */
.bottom-row {
  grid-template-columns: repeat(3, 1fr); /* 三列等宽 */
}

/* 通用组件样式 */
.widget-item,
.full-widget {
  height: 100%;
  overflow: hidden;
}

/* 响应式适配 */
@media (max-width: 1600px) {
  .dashboard-row:first-child {
    grid-template-columns: 1fr 1.8fr;
  }

  .bottom-row {
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  }
}

@media (max-width: 1366px) {
  .dashboard-row:first-child {
    grid-template-columns: 1fr 1.5fr;
  }

  .widget-group {
    grid-template-rows: 1.2fr 1fr;
  }
}
</style>
